/**
 * Copyright 2020 OPSLI 快速开发平台 https://www.opsli.com
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.opsli.modulars.business.emergencyTask.web;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.convert.Convert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.opsli.api.web.business.emergencyTask.EmergencyReportTaskRestApi;
import org.opsli.api.wrapper.business.emergency.EmergencyReportModel;
import org.opsli.api.wrapper.business.emergencyTask.EmergencyReportTaskModel;
import org.opsli.api.wrapper.business.patrolStationRecord.PatrolStationRecordModel;
import org.opsli.api.wrapper.system.user.UserModel;
import org.opsli.common.annotation.RequiresPermissionsCus;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.opsli.api.base.result.ResultVo;
import org.opsli.common.annotation.ApiRestController;
import org.opsli.common.annotation.EnableLog;
import org.opsli.core.base.controller.BaseRestController;
import org.opsli.core.persistence.Page;
import org.opsli.core.persistence.querybuilder.QueryBuilder;
import org.opsli.core.persistence.querybuilder.WebQueryBuilder;
import org.opsli.core.utils.UserUtil;
import org.opsli.modulars.business.app.web.ZkUtils;
import org.opsli.modulars.business.emergency.mapper.EmergencyReportMapper;
import org.opsli.modulars.business.emergencyTask.entity.EmergencyReportTask;
import org.opsli.modulars.business.emergencyTask.mapper.EmergencyReportTaskMapper;
import org.opsli.modulars.business.emergencyTask.service.IEmergencyReportTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 隐患派发任务 Controller
 *
 * @author Ljc
 * @date 2022-03-22 15:34:15
 */
@Api(tags = EmergencyReportTaskRestApi.TITLE)
@Slf4j
@ApiRestController("/emergencyTask")
public class EmergencyReportTaskRestController extends BaseRestController<EmergencyReportTask, EmergencyReportTaskModel, IEmergencyReportTaskService>
    implements EmergencyReportTaskRestApi {

    @Value("${opsli.fileUrl}")
    private  String fileUrl;

    @Autowired
    EmergencyReportMapper reportMapper;
    @Autowired
    EmergencyReportTaskMapper taskMapper;
    /**
    * 隐患派发任务表 查一条
    * @param model 模型
    * @return ResultVo
    */
    @ApiOperation(value = "获得单条隐患派发任务表", notes = "获得单条隐患派发任务表 - ID")
    @RequiresPermissions("emergencytask_select")
    @Override
    public ResultVo<EmergencyReportTaskModel> get(EmergencyReportTaskModel model) {
        // 如果系统内部调用 则直接查数据库
        if(model != null && model.getIzApi() != null && model.getIzApi()){
            model = IService.get(model);
        }
        return ResultVo.success(model);
    }

    /**
    * 隐患派发任务表 查询分页
    * @param pageNo 当前页
    * @param pageSize 每页条数
    * @param request request
    * @return ResultVo
    */
    @ApiOperation(value = "获得分页数据", notes = "获得分页数据 - 查询构造器")
    @RequiresPermissions("emergencytask_select")
    @Override
    public ResultVo<?> findPage(Integer pageNo, Integer pageSize, HttpServletRequest request) {

        QueryBuilder<EmergencyReportTask> queryBuilder = new WebQueryBuilder<>(entityClazz, request.getParameterMap());
        Page<EmergencyReportTask, EmergencyReportTaskModel> page = new Page<>(pageNo, pageSize);
        page.setQueryWrapper(queryBuilder.build());
        page = IService.findPage(page);

        return ResultVo.success(page.getPageData());
    }

    /**
    * 隐患派发任务表 新增
    * @param model 模型
    * @return ResultVo
    */
    @ApiOperation(value = "新增隐患派发任务表数据", notes = "新增隐患派发任务表数据")
    @RequiresPermissions("emergencytask_insert")
    @EnableLog
    @Override
    public ResultVo<?> insert(EmergencyReportTaskModel model) {
        UserModel user= UserUtil.getSysUser();
        String sign = ZkUtils.getRandomStr();
        model.setUserName(model.getRealName());
        /** 任务下发时间 */
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = format.format(date);
        model.setBeginTime(str);
        model.setStationId(model.getStationId()); /** 隐患ID */
        model.setStationName(model.getStationName()); /** 隐患名称 */
        model.setSign(sign);/** 隐患记录标识 */
        model.setDescription(model.getDescription());/** 隐患描述 */
        model.setType("0");/** 种类: 0系统 */
        model.setEmergencyType("0");/** 0进行中 1已结束 */
        //修改隐患表状态
        /** 任务:0未处理 1已派发 2已处理 3审批通过 */
        reportMapper.updateState(model.getStationId());

        model.setManager(user.getId()); /** 任务下发人 */
//        model.setDefectCause("10");
//        model.setDefectResult("ejfiewj");
        // 调用新增方法
        IService.insert(model);
        return ResultVo.success("新增隐患派发任务表成功");
    }

    @Override
    public ResultVo<?> updateTate(String tId) {
        int a= reportMapper.updateStateThree(tId);
        return ResultVo.success("审核通过");
    }

    @Override
    public ResultVo<?> findLast(String xdId) {

        //根据id去任务表里查 任务详情 包括视频图片


        EmergencyReportTask model= taskMapper.findAllByStationId(xdId);


        return ResultVo.success(model);
    }

    @Override
    public ResultVo<Map> getFile(String id){
        Map map=new HashMap();

        EmergencyReportTask model= taskMapper.findAllByStationId(id);
        List<Map> list=new ArrayList<Map>();
        if(null != model){
            if(ZkUtils.isNotBlank(model.getRecordPic())){
                String[] arr=model.getRecordPic().split(",");
                for(String s:arr){
                    Map datamap=new HashMap();
                    datamap.put("src",fileUrl+s);
                    list.add(datamap);
                }
            }
            map.put("pic",list);
            if(ZkUtils.isNotBlank(model.getRecordVideo())){
                map.put("video", fileUrl+model.getRecordVideo());
            }else{
                map.put("video", "");
            }
        }
        return ResultVo.success(map);
    }

    /**
    * 隐患派发任务表 修改
    * @param model 模型
    * @return ResultVo
    */
    @ApiOperation(value = "修改隐患派发任务表数据", notes = "修改隐患派发任务表数据")
    @RequiresPermissions("emergencytask_update")
    @EnableLog
    @Override
    public ResultVo<?> update(EmergencyReportTaskModel model) {
        // 调用修改方法
        IService.update(model);
        return ResultVo.success("修改隐患派发任务表成功");
    }


    /**
    * 隐患派发任务表 删除
    * @param id ID
    * @return ResultVo
    */
    @ApiOperation(value = "删除隐患派发任务表数据", notes = "删除隐患派发任务表数据")
    @RequiresPermissions("emergencytask_update")
    @EnableLog
    @Override
    public ResultVo<?> del(String id){
        IService.delete(id);
        return ResultVo.success("删除隐患派发任务表成功");
    }

    /**
    * 隐患派发任务表 批量删除
    * @param ids ID 数组
    * @return ResultVo
    */
    @ApiOperation(value = "批量删除隐患派发任务表数据", notes = "批量删除隐患派发任务表数据")
    @RequiresPermissions("emergencytask_update")
    @EnableLog
    @Override
    public ResultVo<?> delAll(String ids){
        String[] idArray = Convert.toStrArray(ids);
        IService.deleteAll(idArray);
        return ResultVo.success("批量删除隐患派发任务表成功");
    }


    /**
    * 隐患派发任务表 Excel 导出
    * 注：这里 RequiresPermissionsCus 引入的是 自定义鉴权注解
    *
    * 导出时，Token认证和方法权限认证 全部都由自定义完成
    * 因为在 导出不成功时，需要推送错误信息，
    * 前端直接走下载流，当失败时无法获得失败信息，即使前后端换一种方式后端推送二进制文件前端再次解析也是最少2倍的耗时
    * ，且如果数据量过大，前端进行渲染时直接会把浏览器卡死
    * 而直接开启socket接口推送显然是太过浪费资源了，所以目前采用Java最原始的手段
    * response 推送 javascript代码 alert 提示报错信息
    *
    * @param request request
    * @param response response
    */
    @ApiOperation(value = "导出Excel", notes = "导出Excel")
    @RequiresPermissionsCus("emergencytask_export")
    @EnableLog
    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        // 当前方法
        Method method = ReflectUtil.getMethodByName(this.getClass(), "exportExcel");
        QueryBuilder<EmergencyReportTask> queryBuilder = new WebQueryBuilder<>(entityClazz, request.getParameterMap());
        super.excelExport(EmergencyReportTaskRestApi.SUB_TITLE, queryBuilder.build(), response, method);
    }

    /**
    * 隐患派发任务表 Excel 导入
    * 注：这里 RequiresPermissions 引入的是 Shiro原生鉴权注解
    * @param request 文件流 request
    * @return ResultVo
    */
    @ApiOperation(value = "导入Excel", notes = "导入Excel")
    @RequiresPermissions("emergencytask_import")
    @EnableLog
    @Override
    public ResultVo<?> importExcel(MultipartHttpServletRequest request) {
        return super.importExcel(request);
    }

    /**
    * 隐患派发任务表 Excel 下载导入模版
    * 注：这里 RequiresPermissionsCus 引入的是 自定义鉴权注解
    * @param response response
    */
    @ApiOperation(value = "导出Excel模版", notes = "导出Excel模版")
    @RequiresPermissionsCus("emergencytask_import")
    @Override
    public void importTemplate(HttpServletResponse response) {
        // 当前方法
        Method method = ReflectUtil.getMethodByName(this.getClass(), "importTemplate");
        super.importTemplate(EmergencyReportTaskRestApi.SUB_TITLE, response, method);
    }

}